package org.ysh.service;

import org.springframework.stereotype.Service;
import org.ysh.domain.Department;
import org.ysh.domain.UserDept;
import org.ysh.mapper.UserDeptMapper;
import org.ysh.vo.FormSelectsVo;
import org.ysh.vo.TreeNodeVo;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserDeptService extends BaseService<Integer, UserDept>{

    public UserDeptService(UserDeptMapper baseMapper) {
        super(baseMapper);
    }


    /**
     * 根据用户id查询部门id
     * @param userId
     * @return
     */
    public List<Integer> findDeptIdByUserId(Integer userId){
        return ((UserDeptMapper)this.baseMapper).findDeptIdByUserId(userId);
    }

    /**
     * 根据部门id查询用户id
     * @param deptId
     * @return
     */
    public List<Integer> findUserIdByDeptId(Integer deptId){
        return ((UserDeptMapper)this.baseMapper).findUserIdByDeptId(deptId);
    }

    /**
     * 根据用户id删除用户部门关系
     * @param userId
     */
    public void deleteUserDeptByUser(Integer userId){
        ((UserDeptMapper)this.baseMapper).deleteUserDeptByUser(userId);
    }

    /**
     * 根据部门id删除用户部门关系
     * @param deptId
     */
    public void deleteUserDeptByDept(Integer deptId){
        ((UserDeptMapper)this.baseMapper).deleteUserDeptByDept(deptId);
    }

    public List<FormSelectsVo> treeify(List<Department> departments,List<Integer> deptIds) {
        List<TreeNodeVo> treeNodeVos = TreeNodeVo.buildTree(departments);
        //封装departments为FormSelectsVo
        return getDeptTree(treeNodeVos,deptIds);
    }

    public List<FormSelectsVo> getDeptTree(List<TreeNodeVo> treeNodeVos,List<Integer> deptIds){
        List<FormSelectsVo> formSelectsVos = new ArrayList<>();
        for (TreeNodeVo treeNodeVo : treeNodeVos) {
            FormSelectsVo formSelectsVo = new FormSelectsVo();
            formSelectsVo.setValue(treeNodeVo.getId().toString());
            formSelectsVo.setName(treeNodeVo.getName());
            if(deptIds.contains(treeNodeVo.getId())){
                formSelectsVo.setSelected(true);
            }
            formSelectsVos.add(formSelectsVo);
            if(treeNodeVo.getChildren() != null) {
                formSelectsVo.setChildren(getDeptTree(treeNodeVo.getChildren(),deptIds));
            }
        }
        return formSelectsVos;
    }

}
